import React, { useState, useEffect } from 'react'
import SearchBar from '@c/SearchBar'
import { Button, Table, Tooltip, Tag, Switch, Image, Upload, message, Modal } from 'antd'
import { fetchItems, addMulItems, updateItem, removeItem } from '@a/itemLists'
import {FolderAddOutlined, ExportOutlined,ImportOutlined  } from '@ant-design/icons'
import { exportExcelTpl, writeExcel } from '@u/xlsx'
import { useNavigate } from 'react-router-dom'
export default function ItemLists() {
  const navigate = useNavigate();
  // 点击搜索
  const searchParams = {
    keyWord: '',
    start: '',
    end: ''
  }
  const searchItem = (params) => {
    searchParams.keyWord = params.keyWord;
    searchParams.start = params.range[0];
    searchParams.end = params.range[1];
    getItems();
  }
  // 表格列结构
  const columns = [
    {
      title: '商品名',
      dataIndex: 'itemName',
      key: 'itemName',
    },
    {
      title: '商品价格',
      dataIndex: 'price',
      key: 'price',
    },
    {
      title: '商品描述',
      dataIndex: 'desc',
      render: (value) => {
        return (
          <>
            <Tooltip placement="bottom" title={value}>
              <span>
                {value.substr(0, 15)+'...'}
              </span>
            </Tooltip>
          </>
        )
      },
      key: 'desc',
    },
    {
      title: '销量',
      dataIndex: 'sale',
      render: sale => {
        return (
          <Tag color={sale>500?'red':'green'}>
            {sale}
          </Tag>
        )
      },
      key: 'sale',
    },
    {
      title: '上下架',
      dataIndex: 'onsale',
      render: (onsale, row) => {
        return (
          <Switch defaultChecked={onsale} onChange={
            (checked) => {
              // 行内修改商品上下架状态
              modifyItemOnsale(row.id, checked)
            }
          }/>
        )
      },
      key: 'onsale',
    },
    {
      title: '上架时间',
      dataIndex: 'createAt',
      key: 'createAt',
    },
    {
      title: '封面',
      dataIndex: 'thumb',
      render: thumb => {
        return <Image src={thumb} width={80}/>
      },
      key: 'thumb',
    },
    {
      title: '操作',
      render: (value, row) =>{
        return (
          <>
            <Button 
              type='primary' 
              onClick={
                () => {
                  delItem(row.id)
                }
              }
              danger size='small'>删除</Button>
            <Button onClick={
              () => {
                navigate(`/itemUpdate/${row.id}`)
              }
            } type='primary'  size='small'>编辑</Button>
          </>
        )
      },
      key: 'thumb',
    }
  ]
  const [items, setItems] = useState([]);
  // 列表分页数据
  const [total, setTotal] = useState(0);
  // const [page, setPage] = useState(1);
  // const [pageSize, setPageSize] = useState(10);
  let page = 1;
  let pageSize = 10;
  // 修改了分页页码 一页多少条
  const pageChange = (_page,_pageSize) => {
    page = _page;
    pageSize = _pageSize;
    getItems();
  }
  // 商品列表处理
  const getItems = () => {
    fetchItems({
      page,
      pageSize,
      ...searchParams
    }).then(res => {
      if (res.data.code === 200) {
        setItems(res.data.data.lists)
        setTotal(res.data.data.total)
      }
    })
  }
  // 行内点击开关修改上下架状态
  const modifyItemOnsale = (id, onsale) => {
    // 参数id 上下架状态
    console.log(id, onsale);
    // 发送请求传入参数
    updateItem({
      id,
      onsale
    }).then(res => {
      if (res.data.code === 200) {
        message.success(res.data.msg, 2, () => {
          navigate(0)
        })
      }
    })
  }
  // 删除商品
  const delItem = (id) => {
    // 确认框删除
    Modal.confirm({
      title: '删除商品',
      content: '该操作会彻底删除商品,确定继续吗?',
      onOk: () => {
        removeItem({id}).then(res => {
          if(res.data.code === 200) {
            message.success(res.data.msg, 2, () => {
              navigate(0)
            })
          }
        })
      }
    })
  }
  useEffect(() => {
    getItems()
  }, [])

  // 导出excel模板
  const exportFile = () => {
    // 导出excel模板
    exportExcelTpl([
      {
        商品名: '商品n',
        商品价格:10,
        商品描述: '这是商品描述',
        '上下架(1上架0下架)': 1,
        图片: ''
      }
    ],'xxx表')
  }
  // 导入商品excel模板
  const uploadXlsx = async (file) => {
    writeExcel(file, el => {
      return{
        itemName: el.商品名,
        price: el.商品价格,
        desc: el.商品描述,
        onsale: el['上下架(1上架0下架)'],
        thumb: el.图片
      }
    }).then(data => {
      // 调用批量添加商品
      addMulItems({
        items: data
      }).then(res => {
        if (res.data.code === 200) {
          message.success(res.data.msg, 2, () => {
            navigate(0)
          })
        }
      })
    })
  
  }
  return (
    <div>
      {/* 搜索栏 */}
      <SearchBar handleSearch={searchItem}/>
      {/* /搜索栏 */}
      {/* 操作栏 */}
      <div style={{margin: '15px 0'}}>
        <Button type='primary'
          onClick = {
            () => {
              navigate('/itemAdd')
            }
          }
          icon={<FolderAddOutlined />}>新增商品</Button>
        <Button type='primary' onClick = {
          exportFile
        } icon={<ExportOutlined />}>导出模板</Button>
        <Upload
          accept=".xlsx, .xls"
          action=''
          beforeUpload={(file) => {
            // 导入excel
            uploadXlsx(file)
            return false
          }}
        >
          <Button type='primary' icon={<ImportOutlined />}>批量导入</Button>
        </Upload>
      </div>
      {/* /操作栏 */}
      {/* 表格 */}
      <Table
        rowKey={'id'} 
        pagination={{
        defaultCurrent: page,
        defaultPageSize: pageSize,
        total: total,
        onChange: pageChange
      }} dataSource={items} columns={columns}>

      </Table>
      {/* /表格 */}
    </div>
  )
}
